package com.woniuxy.orderweb.controller;


import com.woniuxy.core.model.Result;
import com.woniuxy.core.util.MyJwtUtil;
import com.woniuxy.core.util.PageInfo;
import com.woniuxy.orderdao.model.Order;
import com.woniuxy.ordermodel.dto.*;
import com.woniuxy.ordermodel.form.CoachListOrderForm;
import com.woniuxy.ordermodel.form.UserListOrderForm;
import com.woniuxy.ordermodel.form.VenueListOrderForm;
import com.woniuxy.orderservice.exception.OrderException;
import com.woniuxy.orderservice.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 冉杰
 * @since 2024-01-15
 */
@Api(tags = {"订单资源接口"})
@RestController
@RequestMapping("/orderInfo")
public class OrderController {
    @Autowired
    private OrderService orderService;
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId",1);
        String token = MyJwtUtil.createUserToken(map, 80);
//        map.put("userId",1);
//        String token = MyJwtUtil.createUserToken(map, 80);
        System.out.println(token);

    }
//    public static void main(String[] args) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("venueId",1);
//        String token = MyJwtUtil.createVenueToken(map, 80);
////        map.put("userId",1);
////        String token = MyJwtUtil.createUserToken(map, 80);
//        System.out.println(token);
//
//    }

    /**
     *
     * @param cardId 次卡id
     * @param token 用户登录token
     * @return
     */
    @ApiOperation("用户端次卡下单")
    @GetMapping("/addCountCard")
    public Result<CountCardOrderDto> addCountCardOrder(Integer cardId,@RequestHeader String token){
        Integer userId = MyJwtUtil.getUserIdByKey(token, "userId");
        CountCardOrderDto dto = orderService.addCountCardOrder(cardId,userId);
        return Result.success("用户次卡下单",dto);
    }

    /**
     * 用户端有效期卡下单
     * @param cardId  有效期卡Id
     * @param token 用户登录token
     * @return
     */
    @ApiOperation("用户端有效期卡下单")
    @GetMapping("/addValidCard")
    public Result<ValidCardOrderDto> addValidCardOrder(Integer cardId,@RequestHeader String token){
        Integer userId = MyJwtUtil.getUserIdByKey(token, "userId");
        ValidCardOrderDto dto = orderService.addValidCardOrder(cardId,userId);
        return Result.success("用户有效期卡下单成功",dto);
    }

    /**
     * 用户端用户端团课下单
     * @param teamReservId 团课预约id
     * @param token 用户登录token
     * @return
     */
    @ApiOperation("用户端团课下单")
    @GetMapping("/addTeamCourse")
    public Result<TeamCourseOrderDto> addTeamCourseOrder(Integer teamReservId, @RequestHeader String token){
        Integer userId = MyJwtUtil.getUserIdByKey(token, "userId");
        TeamCourseOrderDto dto =  orderService.addTeamCourseOrder(teamReservId,userId);
        return Result.success("用户端团课下单成功",dto);
    }


    /**
     * 用户发起订单支付
     * @param orderNum 订单号
     * @return
     * @throws Exception
     */
    @ApiOperation("用户发起订单支付")
    @GetMapping("/pagePay")
    public Result pagePay(String orderNum) throws Exception {
        String html = orderService.pagePay(orderNum);
        return Result.success("发起支付宝网页支付成功",html);
    }

    @ApiOperation("支付宝异步回调私教订单接口")
    @PostMapping("/notifyCoach")
    public String notifyCoach(HttpServletRequest request) throws Exception {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        orderService.notifyCoachHandler(params);
        return "SUCCESS";
    }
    @ApiOperation("支付宝异步回调团课订单接口")
    @PostMapping("/notifyTeam")
    public String notifyTeam(HttpServletRequest request) throws Exception {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        orderService.notifyTeamHandler(params);
        return "SUCCESS";
    }
    @ApiOperation("支付宝异步回调次卡订单接口")
    @PostMapping("/notifyCountCard")
    public String notifyCountCard(HttpServletRequest request) throws Exception {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        orderService.notifyCountCardHandler(params);
        return "SUCCESS";
    }
    @ApiOperation("支付宝异步回调有效期卡订单接口")
    @PostMapping("/notifyValidCard")
    public String notifyValidCard(HttpServletRequest request) throws Exception {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        orderService.notifyValidCardHandler(params);
        return "SUCCESS";
    }
    /**
     * 用户端取消私教课订单
     * @param orderNum 订单号
     * @param token 用户登录token
     * @return
     */
    @ApiOperation("用户端取消私教课订单")
    @GetMapping("/cancelAloneCourse")
    public Result cancelAloneCourse(String orderNum, @RequestHeader String token){
        orderService.cancelAloneCourse(orderNum,token);
        return Result.success("用户取消订单成功");
    }

    /**
     * 教练端私教课下单
     * @param coachReservId 私教课预约id
     * @param token 教练登录token
     * @return
     */
    @ApiOperation("教练端私教课下单")
    @GetMapping("/addAloneCourse.coach")
    public Result<AloneCourseOrderDto> addAloneCourseOrder(Integer coachReservId, @RequestHeader String token){
        Integer coachId = MyJwtUtil.getCoachIdByKey(token, "coachId");
        AloneCourseOrderDto  dto = orderService.addAloneCourseOrder(coachReservId,coachId);
        return Result.success("教练端私教课下单成功",dto);
    }

    /**
     * 用户端条件查看订单详情
     * @param token 用户登录token
     * @return
     */
    @ApiOperation("用户端条件查看自己订单详情")
    @PostMapping("/userList")
    public Result<PageInfo<UserCourseOrderDto>> userListOrder(@RequestBody UserListOrderForm form, @RequestHeader String token){
        Integer userId = MyJwtUtil.getUserIdByKey(token, "userId");
         PageInfo<UserCourseOrderDto> pageInfo =  orderService.userListOrder(form,userId);
        return Result.success("用户端条件查看自己订单成功",pageInfo);
    }

    /**
     * 教练端条件查看自己订单详情
     * @param token 教练登录token
     * @return
     */
    @ApiOperation("教练端条件查看自己订单详情")
    @PostMapping("/coachList.coach")
    public Result<PageInfo<CoachListOrderDto>> coachListOrder(@RequestBody CoachListOrderForm form, @RequestHeader String token){
        Integer coachId = MyJwtUtil.getCoachIdByKey(token, "coachId");
        PageInfo<CoachListOrderDto> pageInfo =  orderService.coachListOrder(form,coachId);
        return Result.success("教练端条件查看自己订单详情成功",pageInfo);
    }
    /**
     * 商家端条件查看自己订单详情
     * @param token 教练登录token
     * @return
     */
    @ApiOperation("商家端条件查看自己订单详情")
    @PostMapping("/venueList.venue")
    public Result<PageInfo<VenueListOrderDto>> venueListOrder(@RequestBody VenueListOrderForm form, @RequestHeader String token){
        Integer venueId = MyJwtUtil.getVenueIdByKey(token, "venueId");
        PageInfo<VenueListOrderDto> pageInfo =  orderService.venueListOrder(form,venueId);
        return Result.success("商家端条件查看自己订单详情成功",pageInfo);
    }

    /**
     * 根据教练id查看订单详情
     * @param coachId 教练id
     * @return
     */
    @ApiOperation("根据教练id查看订单详情")
    @GetMapping("/findByCoachId.coach")
    public Result<List<CoachListOrderDto>> findByCoachId(Integer coachId){
        List<CoachListOrderDto> dtos =  orderService.findByCoachId(coachId);
        return Result.success("查看订单详情成功",dtos);
    }

    /**
     * 根据商家id查看订单详情
     * @param venueId 商家id
     * @return
     */
    @ApiOperation("根据商家id查看订单详情")
    @GetMapping("/findByVenueId.venue")
    public Result<List<VenueListOrderDto>> findByVenueId(Integer venueId){
        List<VenueListOrderDto> dtos =  orderService.findByVenueId(venueId);
        return Result.success("查看订单详情成功",dtos);
    }

    /**
     *
     * @param orderNum 订单号
     * @return 订单详情dto
     */
    @ApiOperation("根据订单号查询订单详情方法")
    @GetMapping("/findByOrderNum")
    public Result<OrderDto> findByOrderNum(String orderNum){
        OrderDto orderDto = orderService.findByOrderNum(orderNum);
        return Result.success("根据订单号查询订单详情成功",orderDto);
    }


    /**
     * 根据订单号修改订单状态
     * @param orderNum 订单号
     * @param orderState 状态枚举
     * @return
     */
    @ApiOperation("根据订单号修改订单状态")
    @GetMapping("/updateOrderStateByOrderNum")
    public Result updateOrderStateByOrderNum(String orderNum,Integer orderState){
        Order order = orderService.getById(orderNum);
        if (ObjectUtils.isEmpty(order)) throw new OrderException(40001,"订单不存在");
        order.setOrderState(orderState);
        orderService.updateById(order);
        return Result.success("修改订单状态成功");
    }

    /**
     * 根据订单号修改评价状态
     * @param orderNum 订单号
     * @param orderEvaluationState 状态枚举
     * @return
     */
    @ApiOperation("根据订单号修改评价状态")
    @GetMapping("/updateOrderEvaluationStateByOrderNum")
    public Result updateOrderEvaluationStateByOrderNum(String orderNum,Integer orderEvaluationState){
        Order order = orderService.getById(orderNum);
        if (ObjectUtils.isEmpty(order)) throw new OrderException(40001,"订单不存在");
        order.setOrderEvaluationState(orderEvaluationState);
        orderService.updateById(order);
        return Result.success("修改订单评价状态成功");
    }

}

